Aller au contenu principal

Arduino Buttons Matrix Midi

Data Fusion Use By

#include <MIDI.h>
MIDI_CREATE_DEFAULT_INSTANCE();

// Configuration of the button matrix
const int ROWS = 3; // Number of rows
const int COLS = 3; // Number of columns
const int rowPins[3] = {12, 11, 10}; // Row pins
const int colPins[3] = {4, 3, 2}; // Column pins
int buttonCState[ROWS][COLS] = {}; // Current state of the buttons
int buttonPState[ROWS][COLS] = {}; // Previous state of the buttons
unsigned long lastDebounceTime[ROWS][COLS] = {0}; // Last time debounce was done
unsigned long debounceDelay = 150; // Debounce delay

void setup() {
Serial.begin(31250); // Standard baud rate for MIDI
// Set row pins as inputs with pull-up resistors
for (int i = 0; i < ROWS; i++) {
pinMode(rowPins[i], INPUT_PULLUP);
}
// Set column pins as outputs
for (int j = 0; j < COLS; j++) {
pinMode(colPins[j], OUTPUT);
digitalWrite(colPins[j], HIGH);
}
}

void loop() {
buttons();
}

void buttons() {
for (int col = 0; col < COLS; col++) {
digitalWrite(colPins[col], LOW); // Set the current column to LOW
for (int row = 0; row < ROWS; row++) {
buttonCState[row][col] = digitalRead(rowPins[row]); // Read the state of the row
if ((millis() - lastDebounceTime[row][col]) > debounceDelay) {
if (buttonPState[row][col] != buttonCState[row][col]) {
lastDebounceTime[row][col] = millis();
if (buttonCState[row][col] == LOW) {
MIDI.sendNoteOn(row * COLS + col, 127, 1); // Send note ON
Serial.print("row:");
Serial.print(row);
Serial.print(" col:");
Serial.print(col);
Serial.println(" button on");
} else {
MIDI.sendNoteOff(row * COLS + col, 0, 1); // Send note OFF
Serial.print("row:");
Serial.print(row);
Serial.print(" col:");
Serial.print(col);
Serial.println(" button off");
}
buttonPState[row][col] = buttonCState[row][col];
}
}
}
digitalWrite(colPins[col], HIGH); // Reset the column to HIGH
}
}